package com.tm.fiverole.security.handler;

import com.baomidou.mybatisplus.extension.api.R;
import com.tm.fiverole.result.Result;
import com.tm.fiverole.result.ResultEnum;
import com.tm.fiverole.ulits.ResponseUtil;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 新建一个处理登陆失败的类
 */
@Component
public class AuthenticationFailureHandlerImpl implements AuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e)  {
        // 这些对于操作的处理类可以根据不同异常进行不同处理
        if (e instanceof UsernameNotFoundException){
            //用户名不存在
            ResponseUtil.out(httpServletResponse, Result.ERROR(ResultEnum.USERNAME_NOT_EXISTED));
        }
        if (e instanceof LockedException){
            //账号已锁定
            ResponseUtil.out(httpServletResponse, Result.ERROR(ResultEnum.ACCOUNT_IS_LOCKED));
        }
        if (e instanceof BadCredentialsException){
            //用户或用户名错误
            ResponseUtil.out(httpServletResponse, Result.ERROR(ResultEnum.USERNAME_OR_PASSWORD_ERROR));
        }
        //登录失败
        ResponseUtil.out(httpServletResponse, Result.ERROR(ResultEnum.LOG_IN_ERROR));
    }

}